package com.hongxun.design.activitys;

import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ListView;

import com.alibaba.fastjson.JSON;
import com.hongxun.design.MyApp;
import com.hongxun.design.R;
import com.hongxun.design.adapters.RegeditAdapter;
import com.hongxun.design.bean.ConsumerInfo;
import com.hongxun.design.bean.CreateDistanceBean;
import com.hongxun.design.constant.Constant;
import com.hongxun.design.interfaces.HeadSecond;
import com.hongxun.design.listeners.ListenerSet;
import com.hongxun.design.mytools.CheckUtil;
import com.hongxun.design.mytools.IconSourse;
import com.hongxun.design.mytools.MString;
import com.hongxun.design.mytools.ToastShow;
import com.hongxun.design.ui.dialogstyle.MyDialog;
import com.hongxun.design.ui.headandbottonpanel.HeadSecondControlPanel;
import com.hongxun.design.utils.DataUtil;
import com.hongxun.design.utils.camerautil.CameraUtil;
import com.hongxun.design.utils.fastjson.FastJsonUtil;
import com.hongxun.design.utils.httputil.HttpStringUtil;
import com.hongxun.design.utils.pathutil.ClipPathUtil;

import java.io.File;
import java.util.List;

/**
 * Created by zerdoor_pc on 2016/6/21.
 * 注册及各种个人信息修改与找回
 */
public class RegeditActivity extends BaseActivity implements HeadSecond {
    /**
     * 通用*
     */
    ListView listView;
    public String type, name;
    String title = "", rightWords = "";
    RegeditAdapter madapter;
    public static String userName = "";
    public static String userPsw = "";
    /**
     * 注册*
     */
    Handler regeditHandler;


    /**
     * 短信*
     */
    Handler smsHandler;

    /**
     * 密保*
     */
    Handler getSecurityProblemHandler;//获取
    Handler securityProblemHandler;//设置
    Handler securityRetrieveHandler;//修改

    /**
     * 修改密码*
     */
    Handler upPsdHandler;//修改密码

    /**
     * 个人信息修改*
     */
    Handler upConsumerInfoHandler;//个人信息修改
    Handler uploadHandle;//个人头像上传
    public static final int Code_Pick = 1;
    public static final int Code_Select = 2;
    public static final String Select_Temp = "Select_Temp";
    ConsumerInfo Info;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_regedit);
        findBar();
        findView();
    }

    private void getIntentData() {
        Bundle bundle = getIntent().getExtras();
        type = bundle.getString(MString.TYPE);
        switch (type) {
            case MString.REGEDIT:
                title = "用户注册";
                rightWords = MString.REGEDIT;
                break;
            case MString.SMS:
                title = MString.SMS;
                rightWords = MString.SURE;
                break;
            case MString.SECRET:
                title = MString.SECRET;
                name = bundle.getString(MString.name);
                userName = bundle.getString(MString.username);
                rightWords = MString.SURE;
                break;

            case MString.SecretSet:
                title = MString.SecretSet;
                rightWords = MString.SURE;
                break;

            case MString.ModifyPassword:
                title = MString.ModifyPassword;
                rightWords = MString.SURE;
                break;

            case MString.PInformationSet:
                title = MString.PInformationSet;
                rightWords = MString.Save;
                break;
        }
    }

    @Override
    public void findBar() {
        getIntentData();
        HeadSecondControlPanel headsecond_layout = (HeadSecondControlPanel) findViewById(R.id.regedit_layout);
        headsecond_layout.initHeadPanel(DataUtil.getsecondbean(rightWords, View.VISIBLE, R.color.bar_right, ListenerSet.back, title, R.color.title, View.VISIBLE, IconSourse.BACK + "", View.VISIBLE));
        headsecond_layout.setClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switch (type) {
                    case MString.REGEDIT:
                        regedit(madapter.getData());
                        break;
                    case MString.SMS:
                        smsRetrieve(madapter.getData(), MString.FindPasswordKey);
                        break;
                    case MString.SECRET:
                        SecurityRetrieve(madapter.getData());
                        break;
                    case MString.SecretSet:
                        SetSecurityProblem(madapter.getData());
                        break;
                    case MString.ModifyPassword:
                        smsRetrieve(madapter.getData(), MString.ModifyPasswordKey);
                        // UpPsd(madapter.getData());
                        break;
                    case MString.PInformationSet:
                        UpConsumerInfo(madapter.getData());
                        break;
                }

            }
        });
    }


    @Override
    protected void onResume() {
        super.onResume();
        MyApp.activity = this;
        mActivity = this;
        baseActivity = this;
    }

    @Override
    protected void findView() {
        super.findView();
        listView = (ListView) findViewById(R.id.regedit_listview);
        switch (type) {
            case MString.REGEDIT:
                madapter = new RegeditAdapter(DataUtil.getRegeditDate(), this);
                listView.setAdapter(madapter);
                addRegeditHandler();
                break;
            case MString.SMS:
                madapter = new RegeditAdapter(DataUtil.getSmsDate(), this);
                listView.setAdapter(madapter);
                addSmsHandler();
                break;
            case MString.SECRET:
                madapter = new RegeditAdapter(DataUtil.getSecretData(name), this);
                listView.setAdapter(madapter);
                addSecurityRetrieveHandler();
                break;
            case MString.SecretSet:
                madapter = new RegeditAdapter(DataUtil.getSecretData(), this);
                listView.setAdapter(madapter);
                addSecurityProblemHandler();
                break;
            case MString.ModifyPassword:
                madapter = new RegeditAdapter(DataUtil.getPswData(), this);
                listView.setAdapter(madapter);
                addSmsHandler();//addUpPsdHandler();
                break;
            case MString.PInformationSet:
                madapter = new RegeditAdapter(DataUtil.getInfoData(), this);
                listView.setAdapter(madapter);
                addUpConsumerInfoHandler();
                addUploadHandler();
                break;
        }
    }

    /**
     * ****************************注册***********************************************************
     */

    private void regedit(List<CreateDistanceBean> beans) {

        for (CreateDistanceBean b : beans) {
            if (b.getValue().length() == 0) {
                ToastShow.showShort(this, b.getTitle() + "不能为空！");
                return;
            }
            if (b.getTitleCode().equals(MString.username)) {
                userName = b.getValue();
                if (!isLetterDigit(userName)){
                    ToastShow.showShort(this, "用户名只能输入数字与字母！");
                    return;
                }
//                Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
//                Matcher m = p.matcher(userName);
//                if (m.find()) {

//                }
            } else if (b.getTitleCode().equals(MString.pwd)) {
                userPsw = b.getValue();
                if (!isLetterDigit(userPsw)){
                    ToastShow.showShort(this, "密码只能输入数字与字母！");
                    return;
                }else if (userPsw.length()>15||userPsw.length()<6){
                    ToastShow.showShort(this, "密码只能输入6-15位字母与数字！");
                    return;
                }
            }

        }

//        Pattern pa = Pattern.compile("^[\u4e00-\u9fa5]*$ ");

        MyApp.HTTP.regedit(regeditHandler, HttpStringUtil.SUCCESSED, beans);
    }

    public static boolean isLetterDigit(String str) {
//        boolean isDigit = false;//定义一个boolean值，用来表示是否包含数字
//        boolean isLetter = false;//定义一个boolean值，用来表示是否包含字母
//        for (int i = 0; i < str.length(); i++) {
//            if (Character.isDigit(str.charAt(i))) {     //用char包装类中的判断数字的方法判断每一个字符
//                isDigit = true;
//            }
//            if (Character.isLetter(str.charAt(i))) {   //用char包装类中的判断字母的方法判断每一个字符
//                isLetter = true;
//            }
//        }
        String regex = "^[a-zA-Z0-9]+$";
//        boolean isRight = isDigit && isLetter && str.matches(regex);
        boolean isRight =  str.matches(regex);
        return isRight;
    }


    private void addRegeditHandler() {
        regeditHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case HttpStringUtil.SUCCESSED:
                        String s = FastJsonUtil.JsonToCheck_String((String) msg.obj);
                        MyDialog.Close();
                        if (s.equals(MString.TRUE)) {
                            ToastShow.showShort(mActivity, "注册成功！");
                            LoginActivity.userName = userName;
                            LoginActivity.userPsw = userPsw;
                             onBackPressed();
                        } else {
                            ToastShow.showShort(mActivity, s);
                            ToastShow.showShort(mActivity, "注册失败！");

                        }

                        break;
                    case HttpStringUtil.ERROR:
                        ToastShow.showShort(mActivity, (String) msg.obj);
                        break;
                }
            }
        };
    }

    /**
     * ****************************短信找回密码****************************************************
     */
    private void smsRetrieve(List<CreateDistanceBean> beans, String key) {
        for (CreateDistanceBean b : beans) {
            if (b.getValue().length() == 0) {
                ToastShow.showShort(this, b.getTitle() + "不能为空！");
                return;
            }
            if (b.getTitleCode().equals(MString.phone)) {
                userName = b.getValue();

            } else if (b.getTitleCode().equals(MString.pwd)) {
                userPsw = b.getValue();

            }

        }
        MyApp.HTTP.SmsRetrieve(smsHandler, HttpStringUtil.SUCCESSED, beans, key);
    }

    private void addSmsHandler() {
        smsHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case HttpStringUtil.SUCCESSED:
                        String s = FastJsonUtil.JsonToCheck_String((String) msg.obj);
                        if (s.equals(MString.TRUE) || s.equals(MString.FALSE)) {
                            try {
                                String token = JSON.parseObject((String) msg.obj).getString(MString.token);
                                MyDialog.dialogForInputPsw(mActivity, smsHandler, token, userName);
                            } catch (Exception e) {
                                ToastShow.showShort(mActivity, "系统异常！");
                            }
                        } else {
                            ToastShow.showShort(mActivity, s);
                            ToastShow.showShort(mActivity, "修改密码失败！");
                        }
                        MyDialog.Close();
                        break;
                    case 1:
                        LoginActivity.userName = userName;
                        LoginActivity.userPsw = userPsw;
                        onBackPressed();
                        ToastShow.showShort(mActivity, "修改密码成功！");
                        break;
                    case HttpStringUtil.ERROR:
                        ToastShow.showShort(mActivity, (String) msg.obj);
                        break;
                }
            }
        };
    }

    /**
     * ****************************密保找回密码****************************************************
     */
    private void SecurityRetrieve(List<CreateDistanceBean> beans) {
        for (CreateDistanceBean b : beans) {
            if (b.getValue().length() == 0) {
                ToastShow.showShort(this, b.getTitle() + "不能为空！");
                return;
            }
        }
        MyApp.HTTP.SecurityRetrieve(securityRetrieveHandler, HttpStringUtil.SUCCESSED, userName, beans);

    }

    private void addSecurityRetrieveHandler() {
        securityRetrieveHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case HttpStringUtil.SUCCESSED:
                        String s = FastJsonUtil.JsonToCheck_String((String) msg.obj);
                        if (s.equals(MString.TRUE) || s.equals(MString.FALSE)) {
                            try {
                                String token = JSON.parseObject((String) msg.obj).getString(MString.token);
                                MyDialog.dialogForInputPsw(mActivity, securityRetrieveHandler, token, userName);
                            } catch (Exception e) {
                                ToastShow.showShort(mActivity, "系统异常！");
                            }
                        } else {
                            ToastShow.showShort(mActivity, s);
                            ToastShow.showShort(mActivity, "修改密码失败！");
                        }
                        MyDialog.Close();
                        break;
                    case 1:
                        LoginActivity.userName = userName;
                        LoginActivity.userPsw = userPsw;
                        mActivity.onBackPressed();
                        ToastShow.showShort(mActivity, "修改密码成功！");
                        break;
                    case HttpStringUtil.ERROR:
                        ToastShow.showShort(mActivity, (String) msg.obj);
                        break;
                }
            }
        };
    }

    /**
     * ********************************设置密保****************************************************
     */
    private void SetSecurityProblem(List<CreateDistanceBean> beans) {
        for (CreateDistanceBean b : beans) {
            if (b.getValue().length() == 0) {
                ToastShow.showShort(this, b.getTitle() + "不能为空！");
                return;
            }
        }
        MyApp.HTTP.SetSecurityProblem(securityProblemHandler, HttpStringUtil.SUCCESSED, beans);
    }

    private void addSecurityProblemHandler() {
        securityProblemHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case HttpStringUtil.SUCCESSED:
                        String s = FastJsonUtil.JsonToCheck_String((String) msg.obj);
                        if (s.equals(MString.TRUE)) {
                            ToastShow.showShort(mActivity, "密保设置成功！");
                            mActivity.onBackPressed();
                        } else {
                            ToastShow.showShort(mActivity, s);
                            ToastShow.showShort(mActivity, "密保设置失败！");
                        }
                        MyDialog.Close();
                        break;
                    case HttpStringUtil.ERROR:
                        ToastShow.showShort(mActivity, (String) msg.obj);
                        break;
                }
            }
        };
    }

    /**
     * ****************************修改密码(old)*******************************************************
     */

    private void UpPsd(List<CreateDistanceBean> beans) {
        for (CreateDistanceBean b : beans) {
            if (b.getValue().length() == 0) {
                ToastShow.showShort(this, b.getTitle() + "不能为空！");
                return;
            }
        }
        MyApp.HTTP.UpPsd(upPsdHandler, HttpStringUtil.SUCCESSED, beans);
    }

    private void addUpPsdHandler() {
        upPsdHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case HttpStringUtil.SUCCESSED:
                        String s = FastJsonUtil.JsonToCheck_String((String) msg.obj);
                        if (s.equals(MString.TRUE)) {
                            ToastShow.showShort(mActivity, "密码修改成功！");
                            mActivity.onBackPressed();
                        } else {
                            ToastShow.showShort(mActivity, s);
                            ToastShow.showShort(mActivity, "密码修改失败！");
                        }
                        MyDialog.Close();
                        break;
                    case HttpStringUtil.ERROR:
                        ToastShow.showShort(mActivity, (String) msg.obj);
                        break;
                }
            }
        };
    }

    /**
     * ****************************个人信息设置*******************************************************
     */

    private void UpConsumerInfo(List<CreateDistanceBean> beans) {
        Info = MyApp.HTTP.UpConsumerInfo(upConsumerInfoHandler, HttpStringUtil.SUCCESSED, beans);
    }

    private void addUpConsumerInfoHandler() {
        upConsumerInfoHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case HttpStringUtil.SUCCESSED:
                        String s = FastJsonUtil.JsonToCheck_String((String) msg.obj);
                        if (s.equals(MString.TRUE)) {
                            MyApp.userInfo.setBean(Info);

                            ToastShow.showShort(mActivity, "个人信息修改成功！");
                            mActivity.onBackPressed();
                        } else {
                            ToastShow.showShort(mActivity, s);
                            ToastShow.showShort(mActivity, "个人信息修改失败！");
                        }
                        MyDialog.Close();
                        break;
                    case HttpStringUtil.ERROR:
                        ToastShow.showShort(mActivity, (String) msg.obj);
                        break;
                }
            }
        };
    }


    /**
     * 头像上传*
     */
    private void Upload(File file) {
        MyApp.HTTP.sendFile(uploadHandle, HttpStringUtil.SUCCESSED, file, MString.HEADER_TYPE);
    }

    private void getFile(String path) {
        String path1 = ClipPathUtil.getPathForImage("UserAvatar");
        CameraUtil.saveToString(path, path1);
        Upload(new File(path1));
    }

    private void addUploadHandler() {
        uploadHandle = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case HttpStringUtil.SUCCESSED:
                        if (FastJsonUtil.JsonToCheck((String) msg.obj)) {
                            String path = FastJsonUtil.JsonToPath((String) msg.obj);
                            madapter.setIcon(path);
                        }
                        MyDialog.Close();
                        break;

                    case HttpStringUtil.ERROR:
                        break;
                }

            }
        };
    }


    /**
     * 相册与拍照回调*
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // 读取相册缩放图片
        if (resultCode != RESULT_OK) {
            return;
        }
        String path;
        switch (requestCode) {
            case Code_Pick:
                path = Environment.getExternalStorageDirectory() + "/" + Constant.TMP_PATH;
                getFile(path);
                break;
            case Code_Select:
                path = CheckUtil.getFilePath(this, data.getData());
                getFile(path);
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }


}
